/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-09-22 10:35:36
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-10-30 15:36:09
 * @FilePath: /GateServer/src/net/logicsystem.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "logicsystem.h"
#include "httpconnection.h"
#include <boost/beast/core/buffers_to_string.hpp>
#include <boost/beast/core/ostream.hpp>
#include <boost/beast/http/field.hpp>
#include <boost/beast/http/fields.hpp>

#include <jsoncpp/json/config.h>
#include <jsoncpp/json/forwards.h>
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>
#include <memory>
#include <ostream>
#include <string>
#include <utility>


#include "../rpc/varifygrpcclient.h"
#include "../util/util.h"
#include "../util/logger.h"
#include "../util/httpresponsebuilder.h"
#include "../validator/registervalidator.h"
#include "../service/Userservice.h"
#include "../validator/resetpswvalidator.h"
#include "../statusclient/statusclient.h"
#include "../validator/loginvalidator.h"
namespace Yizhi {
  
   


    LogicSystem::LogicSystem(){
        
        RegGet("/test_get", [](HttpConnection::ptr connection){
            beast::ostream(connection->m_response.body())<<"hello world";
        });


        RegPost("/get_varifycode",[](HttpConnection::ptr connection){
            auto body_str=beast::buffers_to_string(connection->m_request.body().data());         
            Json::Value root;
            Json::Reader reader;
            Json::Value src_root;
             Json::FastWriter writer;
            bool success=reader.parse(body_str,src_root);
            if(!success){
                root["error"]=Ecode::JSONFLASE;
                auto res=writer.write(root);
                beast::ostream(connection->m_response.body())<<res;
                return ;
            }

            auto email=src_root["email"].asString();
            message::GetVarifyRsp respone=VarifyGrpcClientMgr::GetInstance()->GetVarifyCode(email);
            
            
            root["error"]=respone.error();
            root["email"]=respone.email();
          
            auto res=writer.write(root);
              LOG_INFO(res);
            beast::ostream(connection->m_response.body())<<res;
            return ;
            
        });


        RegPost("/user_register",[](HttpConnection::ptr con){
             auto validator = std::make_shared<RegisterValidator>();
             auto registration_service = std::make_shared<Userservice>(validator);
            auto body_str=beast::buffers_to_string(con->m_request.body().data());
            Json::Value root;
            Json::Reader reader;
            Json::Value src_root;
            con->m_response.set(http::field::content_type,"application/json");
            bool success=reader.parse(body_str,src_root);
            if(!success){
                HttpResponseBuilder::buildJosnParseErrorResponse(con->m_response);
                return ;
            }

            User user(src_root);
            auto result=registration_service->registeruser(user);

            if(result.success){
                 Json::Value success_data;
                 success_data["error"]=Ecode::SUCCESS;
                 success_data["data"]=user.toJson();
                 success_data["message"]="reg success ";
                 HttpResponseBuilder::buildSuccessResponse(con->m_response,success_data);

            }
            else {
                HttpResponseBuilder::buildErrorResponse(con->m_response,result.err_code, result.message);
            }
        });


        RegPost("/user_resetpsw", [](HttpConnection::ptr con){
            auto validator = std::make_shared<Yizhi::ResetPswValidtor>();
            auto resetpsw_service=std::make_shared<Userservice>(validator);
            
            auto body_str=beast::buffers_to_string(con->m_request.body().data());

            Json::Value root;
            Json::Reader reader;
            Json::Value src_root;

            con->m_response.set(http::field::content_type,"application/json");
            bool success=reader.parse(body_str,src_root);
            if(!success){
                HttpResponseBuilder::buildJosnParseErrorResponse(con->m_response);
                return ;
            }
            LOG_DEBUG("success");
            User user(src_root);
            auto result=resetpsw_service->resetpsw(user);
            LOG_INFO(user.getPassword());
            if(result.success){
                  Json::Value success_data;
                 success_data["error"]=Ecode::SUCCESS;
                 success_data["data"]=user.toJson();
                 success_data["message"]="resetpsw success ";
                 HttpResponseBuilder::buildSuccessResponse(con->m_response,success_data);
            }
            else{
                HttpResponseBuilder::buildErrorResponse(con->m_response,result.err_code,result.message);
            }
        });



        RegPost("/user_login", [](HttpConnection::ptr con){

            auto validator = std::make_shared<Yizhi::LoginValidator>();
            auto login_service=std::make_shared<Userservice>(validator);            
            auto body_str=beast::buffers_to_string(con->m_request.body().data());

            Json::Value root;
            Json::Reader reader;
            Json::Value src_root;

            con->m_response.set(http::field::content_type,"application/json");
            bool success=reader.parse(body_str,src_root);
            if(!success){
                HttpResponseBuilder::buildJosnParseErrorResponse(con->m_response);
                return ;
            }
            LOG_DEBUG("success");
            User user(src_root);
            auto result=login_service->login(user);
            LOG_INFO(user.getPassword());
            if(result.success){
                auto reply=StatusClient::GetInstance()->GetChatService(result.uid);
                if(reply.error()==Ecode::RPCFLASE){
                     HttpResponseBuilder::buildErrorResponse(con->m_response,RPCFLASE,"server error");
                }
                else{

                 Json::Value success_data;
                 Json::Value server_data;

                 server_data["host"]=reply.host();
                 server_data["port"]=reply.port();
                 server_data["token"]=reply.tocken();

                 success_data["error"]=Ecode::SUCCESS;
                 success_data["data"]=user.toJson();
                 success_data["message"]="login success ";
                 success_data["chatserver"]=server_data;


                 
                 HttpResponseBuilder::buildSuccessResponse(con->m_response,success_data);
                }
                
            }
            else{
                HttpResponseBuilder::buildErrorResponse(con->m_response,result.err_code,result.message);
            }


        });


        



        
    }

   void LogicSystem::RegGet(std::string method,HttpHandler handler){
        m_gethandler.insert(std::make_pair(method, handler));
    }

    void LogicSystem::RegPost(std::string method,HttpHandler handler){
        m_posthandler.insert(std::make_pair(method,handler));
    }
    bool LogicSystem::HandleGet(std::string path,HttpConnection::ptr con){
        if(m_gethandler.find(path)==m_gethandler.end()){
            return false;
        }
        m_gethandler[path](con);
        return true;

    }


    bool LogicSystem::HandlePost(std::string path,HttpConnection::ptr con){
        if(m_posthandler.find(path)==m_posthandler.end()){
            return false;
        }
        m_posthandler[path](con);
        return true;
    }

    LogicSystem::~LogicSystem(){

    }
   
}